//
//  OAuthViewController.swift
//  我的微博
//
//  Created by ZhangChao on 15/9/3.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate{

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        super.loadView()
        
        view = webView // webView中会做一定的渲染,所以不用设置背景颜色
        
        webView.delegate = self
        
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: UIBarButtonItemStyle.Plain, target: self, action: "autoLogin")
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
//        view.backgroundColor = UIColor.whiteColor()
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oAuthUrl))
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: nil, userInfo: nil)
        
    }
    
    @objc private func autoLogin(){
        
        let js = "document.getElementById('userId').value = '15910732073';document.getElementById('passwd').value = 'zhang8023067'"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
        
        // 关闭动画
        SVProgressHUD.dismiss()
    }

    // 通常在ios中见到返回值为bool的代理方法,直接写return true 返回值一切正常
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("\(request)")
        // 1.判断url的前半部分是不是有回调地址 如果有,继续加载
        let urlString = request.URL!.absoluteString
        printLog("\(urlString)")
        
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUrl){
            
            return true
        }
        // 2.如果有回调地址,检查query,查询字符串是否有'code='
        // query就是?后面的字符串
        if let query = request.URL!.query where query.hasPrefix("code="){
        // 3.如果有,获取 code
            let code = query.substringFromIndex("code=".endIndex)
            printLog(code)
            
            // 4.用网络工具获取token
            
//            NetWorkTools.sharedTools.loadAccessToken(code).subscribeNext({ (result) -> Void in
//                
//                    printLog("\(result)")
//                
//                // 字典转模型
//                let account = UserAccount(dict: result as! [String :AnyObject])
//                
//                NetWorkTools.sharedTools.loadUserInfor(account.uid!, access_token: account.access_token!) .subscribeNext({ (result) -> Void in
//                    
//                    let dict = result as! [String :AnyObject]
//                    
//                    account.name = dict["name"] as? String
//                    account.avatar_large = dict["avatar_large"] as? String
//                    
//                    printLog(account)
//                    
//                    // 保存账号
//                    account.saveUserAccount()
//                    
//                    }, error: { (error) -> Void in
//                        
//                    printLog(error)
//                    }, completed: { () -> Void in
//                        
//                        
//                })
//                }, error: { (error) -> Void in
//                    
//                    print("\(error)")
//            })
            
            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                
                    printLog(error)
                
                }, completed: { () -> Void in
                    
                    printLog("登录完成")
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: "main", userInfo: nil)
            })
            
        }else{
            
            printLog("取消")
        }
        return false
    }
    
    // 添加动画
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}
